<template>
    <div class="app-container">
        <div style="display: flex;margin-bottom: 8px">
            <el-select v-model="advanceSearch.category" clearable placeholder="请选择分类" size="mini">
                <el-option
                        v-for="item in categories"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-input
                    class="width200"
                    size="mini" v-model="advanceSearch.name"
                    prefix-icon="el-icon-search"
                    placeholder="资料文件名"
                    @keydown.enter.native="getList"
            ></el-input>
            <el-input
                    class="width200"
                    size="mini"
                    v-model="advanceSearch.uploadUser"
                    prefix-icon="el-icon-search"
                    placeholder="上传者姓名"
                    @keydown.enter.native="getList"
            ></el-input>
            <el-button style="margin-left: 5px" size="mini" icon="el-icon-search" @click="getList"></el-button>
        </div>
        <!-- Note that row-key is necessary to get a correct row order. -->
        <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row
                  style="width: 100%" :default-sort = "{prop: 'record', order: 'descending'}">
            <el-table-column width="180px" align="center" label="Date">
                <template slot-scope="{row}">
                    <span>{{ row.uploadDate }}</span>
                </template>
            </el-table-column>

            <el-table-column min-width="300px" label="Title">
                <template slot-scope="{row}">
                    <span>{{ row.name }}</span>
                </template>
            </el-table-column>

            <el-table-column width="110px" align="center" label="uploadUser">
                <template slot-scope="{row}">
                    <span>{{ row.uploadUser }}</span>
                </template>
            </el-table-column>

            <el-table-column width="100px" label="Importance">
                <template slot-scope="{row}">
                    <i class="fa fa-star-o" v-if="row.importance===0"/>
                    <i class="fa fa-star" v-else v-for="n in + row.importance" :key="n"/>
                </template>
            </el-table-column>

            <el-table-column align="center" label="Readings" width="110" sortable prop="record">
                <template slot-scope="{row}">
                    <span>{{ row.record }}</span>
                </template>
            </el-table-column>

            <el-table-column class-name="status-col" label="Categories" width="110">
                <template slot-scope="{row}">
                    <el-tag :type="row.category | statusFilter">
                        {{ row.category }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" label="Get" width="80">
                <template slot-scope="{row}">
                    <el-popover
                            placement="top-start"
                            width="162"
                            trigger="hover"
                            content="点击自动复制密码">
                        <el-button type="success" slot="reference" plain class="btn" size="small"
                                   :data-clipboard-text="row.psw" @click="click(row)">
                            <a :href="row.url" target="_blank">获取</a>
                        </el-button>
                    </el-popover>
                </template>
            </el-table-column>

            <el-table-column align="center" label="delete" width="65">
                <template slot-scope="{row}">
                    <el-popconfirm
                            title="确定删除吗？"
                            @onConfirm="onConfirm(row)"
                            @onCancel="onCancel()"
                    >
                        <el-button slot="reference" type="danger" size="small" circle plain icon="el-icon-delete"/>
                    </el-popconfirm>

                </template>
            </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: space-between;margin-top: 5px">
            <el-button size="small" icon="el-icon-plus" plain @click="dialog=true">上传资料</el-button>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-drawer
                title="上传资料"
                :before-close="handleClose"
                :with-header="false"
                :visible.sync="dialog"
                direction="ltr"
                custom-class="demo-drawer"
                ref="drawer"
        >
            <div style="width: 400px;margin-top: 20px">
                <el-form :model="learnResource" label-width="100px" :rules="rules" ref="ruleForm">
                    <el-form-item label="资料文件名" prop="name">
                        <el-input size="small" v-model="learnResource.name" placeholder="分享的文件名称（永久）"></el-input>
                    </el-form-item>
                    <el-form-item label="文件类别" size="small" prop="category">
                        <el-select v-model="learnResource.category" clearable placeholder="请选择分类" size="small">
                            <el-option
                                    v-for="item in categories"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="url地址" prop="url">
                        <el-input size="small" v-model="learnResource.url" placeholder="带http的url地址"></el-input>
                    </el-form-item>
                    <el-form-item label="提取密码">
                        <el-input size="small" v-model="learnResource.psw" placeholder="有设置提取密码的就填"></el-input>
                    </el-form-item>
                </el-form>
                <div style="display: flex;justify-content: flex-end">
                    <el-button @click="cancelForm">取 消</el-button>
                    <el-button type="primary" @click="add" v-loading.fullscreen.lock="fullscreenLoading">确定</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
    import Sortable from 'sortablejs'
    import Clipboard from 'clipboard'

    const btnCopy = new Clipboard('.btn')
    const url = '/resource/study/'
    let maxRecord = 0

    export default {
        name: 'DragTable',
        filters: {
            statusFilter(status) {
                if (status === '嵌入式' || status === '考研') {
                    return 'primary'
                } else if (status === '后端' || status === '前端') {
                    return 'success'
                } else if (status === '大数据') {
                    return 'warning'
                } else if (status === '人工智能') {
                    return 'danger'
                } else if (status === '其他') {
                    return 'info'
                }
            }
        },
        data() {
            return {
                list: [],
                total: null,
                listLoading: true,
                learnResource: {
                    id: '',
                    url: '',
                    psw: '',
                    category: '',
                    name: '',
                    uploaddate: '',
                    record: 0,
                    uploaduser: '',
                },
                fullscreenLoading:false,
                sortable: null,
                oldList: [],
                newList: [],
                size: 10,
                page: 1,
                categories: [
                    {
                        value: '嵌入式',
                        label: '嵌入式'
                    },
                    {
                        value: '前端',
                        label: '前端'
                    },
                    {
                        value: '后端',
                        label: '后端'
                    },
                    {
                        value: '大数据',
                        label: '大数据'
                    },
                    {
                        value: '人工智能',
                        label: '人工智能'
                    },
                    {
                        value: '考研',
                        label: '考研'
                    },
                    {
                        value: '其他',
                        label: '其他'
                    },
                ],
                advanceSearch: {
                    uploadUser: '',
                    category: '',
                    name: ''
                },
                dialog: false,
                rules: {
                    name: [
                        {required: true,message:'请输入资料名称',trigger:'blur'}
                    ],
                    url: [
                        {required: true,message:'请输入资料url地址',trigger:'blur'}
                    ],
                    category: [
                        {required: true,message:'请选择分类',trigger:'change'}
                    ],
                }
            }
        },
        created() {
            this.getList()
        },
        methods: {
            getList() {
                this.listLoading = true
                let nUrl = url + '?page=' + this.page + '&size=' + this.size +
                    '&category=' + this.advanceSearch.category + '&name=' + this.advanceSearch.name +
                    '&uploadUser=' + this.advanceSearch.uploadUser
                this.getRequest(nUrl).then(resp => {
                    // console.log(nUrl);
                    if (resp) {
                        let list = []
                        this.list = []
                        this.total = resp.total
                        maxRecord = 0
                        for (let n of resp.data) {
                            maxRecord = Math.max(maxRecord, n.record)
                        }
                        for (let n of resp.data) {
                            let obj = {
                                id: n.id,
                                url: n.url,
                                psw: n.psw,
                                category: n.category,
                                name: n.name,
                                uploadDate: n.uploaddate,
                                record: n.record,
                                uploadUser: n.uploaduser,
                                importance: Math.floor((n.record * 1.0 / (maxRecord === 0 ? 1 : maxRecord)) * 5)
                            }
                            list.push(obj)
                        }
                        this.list = list
                        this.maxRecord = maxRecord
                        this.listLoading = false
                        this.$nextTick(() => {
                            this.setSort()
                        })
                    }
                    this.emptySearch()
                })
            },
            setSort() {
                const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
                this.sortable = Sortable.create(el, {
                    ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
                    setData: function (dataTransfer) {
                        dataTransfer.setData('Text', '')
                    },
                })
            },
            onConfirm(row) {
                this.deleteRequest(url + row.id).then(resp => {
                    if (resp) {
                        this.getList()
                    }
                })
            },
            onCancel() {
                this.$notify.info({
                    message: '已取消删除'
                });
            },
            handleSizeChange(val) {
                this.size = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getList();
            },
            emptySearch() {
                this.advanceSearch.name = ''
                this.advanceSearch.uploadUser = ''
                this.advanceSearch.category = ''
            },
            handleClose(done) {
                this.dialog = false
            },
            cancelForm() {
                this.dialog = false;
            },
            add() {
                this.$confirm('确认上传此资源?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.fullscreenLoading = true
                    this.$refs['ruleForm'].validate(valid=>{
                        if(valid){
                            this.learnResource.uploaduser = JSON.parse(window.sessionStorage.getItem('user')).name
                            this.postRequest(url,this.learnResource).then(resp=>{
                                if(resp){
                                    this.getList();
                                    this.dialog=false
                                }
                            })
                        }
                    })
                    this.fullscreenLoading = false
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                    this.fullscreenLoading = false
                });
            },
            click(row){
              this.putRequest(url+'click/?learnId='+row.id+'&userId='+JSON.parse(window.sessionStorage.getItem('user')).id);
            },


            
        }
    }
</script>

<style>
    .sortable-ghost {
        opacity: .8;
        color: #fff !important;
        background: #42b983 !important;
    }

    .width200 {
        width: 200px;
        /*margin-right: 5px;*/
        margin-left: 5px;
    }
</style>

<style scoped>
    .icon-star {
        margin-right: 2px;
    }

    .drag-handler {
        width: 20px;
        height: 20px;
        cursor: pointer;
    }

    .show-d {
        margin-top: 15px;
    }
</style>

<style scoped>
    /* 用来设置当前页面element全局table 选中某行时的背景色*/
    /deep/ .el-table__body tr.current-row>td{
        background-color: rgba(35,29,37,.9) !important;
        /* color: #f19944; */  /* 设置文字颜色，可以选择不设置 */
    }

    /deep/ .el-table, /deep/ .el-table__expanded-cell {
        background-color: rgba(35,29,37,.26);
    }
    /deep/ .el-table th, /deep/ .el-table tr, /deep/ .el-table td{
        background-color: rgba(35,29,37,.26);
    }
    /deep/ .el-table--enable-row-transition, /deep/ .el-table__body td, /deep/ .el-table .cell{
        background-color: rgba(35,29,37,.1);;
    }
    /deep/ .el-table .cell{
        color: rgba(256, 256, 256, 0.78);
    }
</style>
